
import logging
import httpx
import aiofiles
from pydantic import BaseModel
from fastapi import Request, Response
from gurren.app import app
log = logging.getLogger(__name__)

VERIFY_URL = "https://www.google.com/recaptcha/api/siteverify"
SECRET = ""

class RecaptchaValidateReq(BaseModel):
    response: str


@app.post('/ws/recaptcha/validate')
async def recaptcha_validate(data: RecaptchaValidateReq, req: Request, res: Response):
    valid = await validate(data.response)
    if valid:
        res.set_cookie("x-gurren-captcha", "Yes", max_age=60)
    return { 'valid':  valid }


async def ensure_secret():
    global SECRET
    if SECRET: return SECRET

    for fname in ['/run/secrets/recaptcha_secret', '~/gurren/recaptcha_secret.txt']:
        try:
            # let's play with async file IO
            async with aiofiles.open(fname) as f:
                SECRET = (await f.read()).strip()
            log.info('captcha use secret=%s', fname)
            return SECRET
        except Exception as ex:
            log.debug('captcha not found secret=%s', fname)
    log.error('captcha no secrets')
    return ""

async def validate(user_response: str): 
    async with httpx.AsyncClient() as c:
        log.debug('captcha validate=%s', user_response)
        r = await c.post(VERIFY_URL, params={'response': user_response,
                                             'secret': await ensure_secret()})
        log.debug('captcha verdict=%s', r.json())
    
    return bool((r.json() or {}).get('success'))


# WOW! Easy proxy with httpx streaming!

from starlette.background import BackgroundTask
from starlette.responses import StreamingResponse

client = httpx.AsyncClient()

async def stream(request):
    req = client.build_request("GET", "https://www.python-httpx.org/async/")
    r = await client.send(req, stream=True)
    return StreamingResponse(r.aiter_text(), background=BackgroundTask(r.aclose))
